package com.tanx.cqrs.saga.impl;

import com.tanx.cqrs.event.Event;
import com.tanx.cqrs.saga.SagaHandlerInstance;
import com.tanx.cqrs.saga.SagaInfo;
import lombok.Data;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * saga实现类
 */
@Data
public class MemorySagaInfoImpl implements SagaInfo {
    private String sagaId;
    private Long timeout;
    private Date createTime;
    private Set<Event> executeEvents = new HashSet<>();

    private String sagaClass;
    private String repositoryClass;
    private String methodName;
    private SagaStatus status = SagaStatus.START;

    public MemorySagaInfoImpl(String sagaId, SagaHandlerInstance instance, Event event) {
        this.sagaId = sagaId;
        this.executeEvents.add(event);
        this.createTime = new Date();
        this.timeout = instance.getTimeOut();

        this.sagaClass = instance.getBean().getClass().getName();
        this.methodName = instance.getMethod().getName();
        this.repositoryClass = instance.getRepository().getClass().getName();
    }

    /**
     * 空构造函数用于数据库
     */
    public MemorySagaInfoImpl() {
    }

    @Override
    public boolean timeout(long timeOut) {
        long time = new Date().getTime();
        long l = time - createTime.getTime();
        return l > timeout;
    }

    @Override
    public boolean contains(Event event) {
        return executeEvents.parallelStream().anyMatch(item -> item.getUuid().equals(event.getUuid()));
    }
}
